<template>
  <div class="weather-service">
    <div class="search-box">
      <el-input
        v-model="searchLocation"
        placeholder="请输入地点"
        class="location-input"
      >
        <template #append>
          <el-button @click="searchWeather" :loading="loading">
            查询天气
          </el-button>
        </template>
      </el-input>
      
      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length">
        <div class="history-title">
          <span>搜索历史</span>
          <el-button type="text" @click="clearHistory">清空历史</el-button>
        </div>
        <div class="history-tags">
          <el-tag
            v-for="address in searchHistory"
            :key="address"
            class="history-tag"
            @click="quickSearch(address)"
          >
            {{ address }}
          </el-tag>
        </div>
      </div>
    </div>

    <div v-if="weatherData" class="weather-content">
      <div class="current-weather">
        <h2>{{ weatherData.location }} 当前天气</h2>
        <div class="weather-info">
          <div class="temp">{{ weatherData.current.temperature }}°C</div>
          <div class="weather">{{ weatherData.current.weather }}</div>
          <div class="time">更新时间：{{ formatDateTime(weatherData.current.time) }}</div>
        </div>
      </div>

      <div class="forecast">
        <h3>未来天气预报</h3>
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in weatherData.forecast" :key="item.date">
            <el-card class="forecast-card">
              <div class="date">{{ formatDate(item.date) }}</div>
              <div class="weather">{{ item.weather }}</div>
              <div class="temp-range">
                {{ item.max_temp }}°C / {{ item.min_temp }}°C
              </div>
              <div class="details">
                <p>日出：{{ formatTime(item.sunrise) }}</p>
                <p>日落：{{ formatTime(item.sunset) }}</p>
                <p>风速：{{ item.wind_speed }}km/h</p>
                <p>降水量：{{ item.precipitation }}mm</p>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-empty
      v-else-if="!loading"
      description="请输入地点查询天气"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { weatherApi } from '@/api/public/weather'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const loading = ref(false)
const searchLocation = ref('')
const weatherData = ref<any>(null)
const searchHistory = ref<string[]>([])

// 从 localStorage 加载搜索历史
const loadSearchHistory = () => {
  const history = localStorage.getItem('weatherSearchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
}

// 保存搜索历史
const saveSearchHistory = (address: string) => {
  if (!searchHistory.value.includes(address)) {
    searchHistory.value = [address, ...searchHistory.value].slice(0, 10) // 最多保存10条
    localStorage.setItem('weatherSearchHistory', JSON.stringify(searchHistory.value))
  }
}

// 清空搜索历史
const clearHistory = () => {
  ElMessageBox.confirm('确定要清空搜索历史吗？', '提示', {
    type: 'warning'
  }).then(() => {
    searchHistory.value = []
    localStorage.removeItem('weatherSearchHistory')
    ElMessage.success('搜索历史已清空')
  })
}

// 快速搜索
const quickSearch = (address: string) => {
  searchLocation.value = address
  searchWeather()
}

const searchWeather = async () => {
  if (!searchLocation.value) {
    ElMessage.warning('请输入地点')
    return
  }

  loading.value = true
  try {
    const response = await weatherApi.getWeather(searchLocation.value)
    if (response.code === 0) {
      weatherData.value = response.data
      saveSearchHistory(searchLocation.value) // 保存到搜索历史
    } else {
      ElMessage.error(response.message || '获取天气信息失败')
    }
  } catch (error) {
    console.error('获取天气失败:', error)
    ElMessage.error('获取天气信息失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime: string) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm')
}

const formatDate = (date: string) => {
  return dayjs(date).format('MM月DD日')
}

const formatTime = (datetime: string) => {
  return dayjs(datetime).format('HH:mm')
}

onMounted(() => {
  loadSearchHistory()
})
</script>

<style scoped>
.weather-service {
  padding: 20px;
}

.search-box {
  max-width: 500px;
  margin: 0 auto 30px;
}

.location-input {
  width: 100%;
}

.weather-content {
  max-width: 1000px;
  margin: 0 auto;
}

.current-weather {
  text-align: center;
  margin-bottom: 40px;
}

.weather-info {
  margin-top: 20px;
}

.temp {
  font-size: 48px;
  font-weight: bold;
  color: #409EFF;
}

.weather {
  font-size: 24px;
  margin: 10px 0;
}

.time {
  color: #666;
  font-size: 14px;
}

.forecast {
  margin-top: 40px;
}

.forecast h3 {
  margin-bottom: 20px;
}

.forecast-card {
  text-align: center;
  margin-bottom: 20px;
}

.forecast-card .date {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.forecast-card .weather {
  font-size: 16px;
  margin: 10px 0;
}

.forecast-card .temp-range {
  color: #409EFF;
  font-size: 16px;
  margin-bottom: 15px;
}

.forecast-card .details {
  text-align: left;
  color: #666;
  font-size: 14px;
}

.forecast-card .details p {
  margin: 5px 0;
}

.search-history {
  margin-top: 15px;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
}

.history-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.history-tag:hover {
  transform: scale(1.05);
}
</style> 